package com.github.shiqiyue.app.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.dozer.DozerConverter;

import java.text.ParseException;
import java.util.Date;

/***
 * 时间转Date
 * @author wenyao.wu
 * @since 2020/7/23
 */
@Slf4j
public class StringToDateConverter extends DozerConverter<String, Date> {

    public StringToDateConverter() {
        super(String.class, Date.class);
    }

    @Override
    public Date convertTo(String source, Date destination) {
        if (StringUtils.isBlank(source)) {
            destination = null;
            return null;
        }
        try {
            destination = DateUtils.parse(source, DateUtils.YYYY_MM_DD);
        } catch (ParseException e) {
            try {
                destination = DateUtils.parse(source, DateUtils.YYYY_MM_DD_HH_MM_SS);
            } catch (ParseException parseException) {
                log.error("转换失败", parseException);
            }
        }
        return destination;
    }

    @Override
    public String convertFrom(Date source, String destination) {
        if (source == null) {
            destination = null;
            return null;
        }
        destination = DateUtils.format(source, DateUtils.YYYY_MM_DD);
        return destination;
    }
}
